package com.campsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campsys.entity.Course;
import com.campsys.entity.RollCall;
import com.campsys.entity.User;
import com.campsys.entity.CourseStudent;
import com.campsys.mapper.CourseMapper;
import com.campsys.mapper.RollCallMapper;
import com.campsys.mapper.CourseStudentMapper;
import com.campsys.service.CourseService;
import com.campsys.service.dto.CourseDTO;
import com.campsys.service.dto.CourseQueryDTO;
import com.campsys.service.dto.RollCallDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class CourseServiceImpl implements CourseService {
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private RollCallMapper rollCallMapper;
    
    @Autowired
    private CourseStudentMapper courseStudentMapper;
    
    @Override
    public IPage<Course> getCourseList(Page<Course> page, CourseQueryDTO queryDTO, Long teacherId) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getTeacherId, teacherId);
        
        // 添加查询条件
        if (StringUtils.isNotBlank(queryDTO.getName())) {
            wrapper.like(Course::getName, queryDTO.getName());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(Course::getStatus, queryDTO.getStatus());
        }
        
        wrapper.orderByDesc(Course::getCreateTime);
        return courseMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public void addCourse(CourseDTO courseDTO, Long teacherId) {
        Course course = new Course();
        BeanUtils.copyProperties(courseDTO, course);
        
        course.setTeacherId(teacherId);
        course.setCreateTime(LocalDateTime.now());
        course.setCreateBy(teacherId.toString());
        
        courseMapper.insert(course);
    }
    
    @Override
    @Transactional
    public void updateCourse(CourseDTO courseDTO, Long teacherId) {
        // 验证课程是否存在且属于该教师
        Course existingCourse = validateCourseOwnership(courseDTO.getId(), teacherId);
        
        Course course = new Course();
        BeanUtils.copyProperties(courseDTO, course);
        
        course.setTeacherId(teacherId);  // 确保教师ID不变
        course.setUpdateTime(LocalDateTime.now());
        course.setUpdateBy(teacherId.toString());
        
        courseMapper.updateById(course);
    }
    
    @Override
    @Transactional
    public void deleteCourse(Long id, Long teacherId) {
        // 验证课程是否存在且属于该教师
        Course course = validateCourseOwnership(id, teacherId);
        
        // 检查是否有学生正在学习该课程
        LambdaQueryWrapper<CourseStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseStudent::getCourseId, id)
              .eq(CourseStudent::getStatus, 1);  // 1-正常状态
        if (courseStudentMapper.selectCount(wrapper) > 0) {
            throw new IllegalArgumentException("该课程有学生正在学习，无法删除");
        }
        
        // 检查是否有点名记录
        LambdaQueryWrapper<RollCall> rollCallWrapper = new LambdaQueryWrapper<>();
        rollCallWrapper.eq(RollCall::getCourseId, id);
        if (rollCallMapper.selectCount(rollCallWrapper) > 0) {
            throw new IllegalArgumentException("该课程有点名记录，无法删除");
        }
        
        courseMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status, Long teacherId) {
        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("无效的状态值");
        }
        
        // 验证课程是否存在且属于该教师
        Course course = validateCourseOwnership(id, teacherId);
        
        // 如果要关闭课程，检查是否有学生正在学习
        if (status == 0) {
            LambdaQueryWrapper<CourseStudent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseStudent::getCourseId, id)
                  .eq(CourseStudent::getStatus, 1);  // 1-正常状态
            if (courseStudentMapper.selectCount(wrapper) > 0) {
                throw new IllegalArgumentException("该课程有学生正在学习，无法关闭");
            }
        }
        
        Course updateCourse = new Course();
        updateCourse.setId(id);
        updateCourse.setStatus(status);
        updateCourse.setUpdateTime(LocalDateTime.now());
        updateCourse.setUpdateBy(teacherId.toString());
        
        courseMapper.updateById(updateCourse);
    }
    
    @Override
    public IPage<User> getCourseStudents(Page<User> page, Long courseId, Long teacherId) {
        // 验证课程是否存在且属于该教师
        validateCourseOwnership(courseId, teacherId);
        
        return courseMapper.selectCourseStudents(page, courseId);
    }
    
    @Override
    @Transactional
    public void createRollCall(RollCallDTO rollCallDTO, Long teacherId) {
        // 验证课程是否存在且属于该教师
        validateCourseOwnership(rollCallDTO.getCourseId(), teacherId);
        
        // 验证时间
        if (rollCallDTO.getStartTime().isAfter(rollCallDTO.getEndTime())) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }
        
        RollCall rollCall = new RollCall();
        BeanUtils.copyProperties(rollCallDTO, rollCall);
        
        rollCall.setStatus(0);  // 0-未开始
        rollCall.setCreateTime(LocalDateTime.now());
        rollCall.setCreateBy(teacherId.toString());
        
        rollCallMapper.insert(rollCall);
    }
    
    @Override
    public IPage<RollCall> getRollCallList(Page<RollCall> page, Long courseId, Long teacherId) {
        // 验证课程是否存在且属于该教师
        validateCourseOwnership(courseId, teacherId);
        
        LambdaQueryWrapper<RollCall> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RollCall::getCourseId, courseId);
        wrapper.orderByDesc(RollCall::getCreateTime);
        
        return rollCallMapper.selectPage(page, wrapper);
    }
    
    private Course validateCourseOwnership(Long courseId, Long teacherId) {
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new IllegalArgumentException("课程不存在");
        }
        if (!course.getTeacherId().equals(teacherId)) {
            throw new IllegalArgumentException("无权操作此课程");
        }
        return course;
    }
} 